package ls.jpa.chapter9.service;

import ls.jpa.chapter9.entities.Employee;

import javax.persistence.*;
import java.util.List;

/**
 * @author Barudisshu
 */
public class EmployeeService {

    protected EntityManager em;

    public EmployeeService(EntityManager em) {
        this.em = em;
    }

    public Employee createEmployee(int id, String name, long salary) {
        Employee emp = new Employee();
        emp.setId(id);
        emp.setName(name);
        emp.setSalary(salary);
        Query query = em.createNativeQuery("INSERT INTO db_test.t_employee(id,name,salary) VALUES (?, ?, ?)");
        query.setParameter(1, emp.getId());
        query.setParameter(2, emp.getName());
        query.setParameter(3, emp.getSalary());

        int row = query.executeUpdate();
        if (row < 1)
            return null;
        else
//        em.merge(emp);
        return emp;
    }

    public void removeEmployee(int id) {
        Employee emp = findEmployee(id);
        if (emp != null) {
            em.remove(emp);
        }
    }

    public Employee raiseEmployeeSalary(int id, long raise) {
        Employee emp = em.find(Employee.class, id);
        if (emp != null) {
            emp.setSalary(emp.getSalary() + raise);
        }
        return emp;
    }

    public Employee findEmployee(int id) {
        return em.find(Employee.class, id);
    }

    public List<Employee> findAllEmployees() {
        TypedQuery<Employee> query = em.createQuery("select e from Emp e", Employee.class);
        return query.getResultList();
    }
}
